<?php

class Files
{
	protected $_transfer;
	
	//---------------------------------------MEDIA-------------------------------------------
	
	
	public function getIdTags( $filename )
	{

		try 
		{
	    	$id3 = new Zend_Media_Id3v1($filename);
	    	$result['title'] = $id3->getTitle();
			$result['album'] = $id3->getAlbum();
			$result['genre'] = $id3->getGenre();
			$result['artist'] = $id3->getArtist();
			$result['year'] = $id3->getYear();
			$result['comment'] = $id3->getComment();
			$result['track'] = $id3->getTrack();
		} catch (Zend_Media_Id3_Exception $e) 
		{
			try {
	    	$id3 = new Zend_Media_Id3v2( $filename );
			$result['title'] = $id3->tit2->text;
			$result['album'] = $id3->talb->text;
			$result['genre'] = $id3->tcon->text;
			$result['year'] = $id3->tyer->text;
			$result['track'] = $id3->trck->text;
			$result['comment'] = $id3->comm->text;
			$result['artist'] = $id3->tpel->text;
			}catch (Zend_Media_Id3_Exception $e) 
		{
			die();
		}
			//$result = $id3->getFrames();
			
	    }
	
			if ( !empty( $result ) )	
			{
				return $result;
			}
			else
			{
				return false;
			}
	}
	
	public function setIdTags( $filename , $data )
	{


	    	$id3 = new Zend_Media_Id3v1($filename);
	    	$id3->setTitle( $data['title'] );
	    	$id3->setAlbum( $data['album'] );
	    	$id3->setGenre( $data['genre'] );
	    	$id3->setArtist( $data['artist'] );
	    	$id3->setYear( $data['year'] );
	    	$id3->setComment( $data['comment'] );
	    	$id3->setTrack( $data['track'] );
	    	
	    	$id3->write();
	    	
	    	//TODO : saveToDataBase();
	    	

	}
	
	//---------------------------------------------------------------------------------------
	
	
	
	
	
	
  	public function __construct()
    {
	   $this->_transfer = new Zend_Db_Table('transfer');
    }
	
    public function buildTree()
    {
        return $this->get_dirs();
    }

 	public function rename($PMID, $Name, $type)
    {	
    		global $newName;
    		if ($type == 'file' || $type == 'folder')
    		{
    			$dir = dirname($PMID);
    			$newName = $dir . "/" . iconv("UTF-8", "cp1251" , $Name);
    		}
    		if ( @rename( $PMID , $newName ) )
    		{
    			$item['id'] = $newName;
        		$item['type'] = $type;
        		$item['status'] = 1;
    		}
    		else {
    			$item['status'] = 0;
    		}
    		return $item;
    }
    
	public function remove($PMID)
    {
    	if ( file_exists($PMID) )
    	{
    		unlink($PMID); 
    	}	
    }
    
	public function getFiles( $allGetFiles , $allId )
    {
    	$usersDAO = new Application_Model_Users();
    	$userId = $usersDAO->getCurrentUser()->id;
    	if ( !file_exists( APPLICATION_PATH . "/store/$userId/downloads") )
    	{
    		mkdir( APPLICATION_PATH . "/store/$userId/downloads" );
    	}
    	$i=-1;
    	foreach ( $allGetFiles as $key=>$value )
    	{
    		$i++;
    		copy( $value , APPLICATION_PATH . "/store/$userId/downloads/" . basename( $value ) );
    		$this->deleteFromDB( $allId[$i] );
    		
    	}
    	
    }
    
    public function deleteFromDB( $id )
    {
    	$Row = $this->_transfer->find($id)->current();
    	$Row->delete();
    }
    
  	public function deleteTransfer( $files )
    {
    	foreach ( $files as $key => $value )
    	{
    		$Row = $this->_transfer->find($value)->current();
    		$Row->delete();
    	}
    }
    
	public function transfer( $usersCheck , $file )
    {
    	$usersDAO = new Application_Model_Users();
    	$userId = $usersDAO->getCurrentUser()->id;
    	foreach ( $usersCheck as $key => $value )
    	{
    		$Row = $this->_transfer->createRow();
    		$Row->user = $value;
    		$Row->file = $file;
    		$Row->date = new Zend_Db_Expr( "NOW()" );
    		$Row->fromid = $userId;
    		$Login = $usersDAO->getOneUser( $userId  );
    		$Row->login = $Login['Login'];
    		$Row->save();
    	}
    }
    
    public function transfetIn( $userId )
    {
    	return  $this->_transfer->fetchAll($this->_transfer->select()->where( " user = ? ", $userId ))->toArray();
    	
    }
    
	public function getInfo($ID)
    {
    	global $result;
    	$result = array();
    	$ID = iconv("UTF-8", "cp1251" , $ID);
    	$usersDAO = new Application_Model_Users();
    	$userId = $usersDAO->getCurrentUser()->id;
    	if ( file_exists($ID) )
    	{
    		$result['m'] = date("d/m/Y H:i:s", filemtime($ID)); 
    		$result['a'] = date("d/m/Y H:i:s", fileatime($ID));
    		$result['c'] = date("d/m/Y H:i:s", filectime($ID));
    		$result['name'] = basename( $ID );
    		$result['name'] = iconv("cp1251", "UTF-8" , $result['name']);
    		$result['path'] =  $ID;
    		$result['userId'] = $userId;
    		$result['size'] = ( is_file( $ID )) ? filesize( $ID ) : 'none';
    		return $result;
    	}else
    	{
    		return false;
    	}	
    	
    }
    
    public function upload( $id,$parentId, $fileName) 
    {

    		return copy($id, $parentId . "/" . $fileName );

    }
    
	public function copy($id,$parentId)
    {
    	if ( file_exists($id) )
    	{
   			 copy($id, $parentId . "/" . basename( $id ));
   			 $item['id'] = $parentId;
        	 $item['status'] = 1;
    	}	
    	return $item;
    }
    
	public function move($id,$parentId)
    {
    	if ( file_exists($id) )
    	{
    		copy($id, $parentId . "/" . basename( $id ));
    		$this->remove($id);
   			$item['id'] =$parentId . "/" . basename( $id );
        	$item['status'] = 1;
    	}	
    	return $item;
    }
    
	public function add($PMID,$Name, $Type)
    {
    	$usersDAO = new Application_Model_Users();
        $userId = $usersDAO->getCurrentUser()->id;
        $Name = iconv("UTF-8", "cp1251" , $Name);		
        if ( empty($PMID) ) 
        {
        	$PMID = APPLICATION_PATH . "/store/$userId";
        }
    	$item = array('data'=>'titile', 'children'=>array());
    	$item['id'] = $PMID  . "/" . $Name;
        $item['type'] = $Type;
        $item['children'] = $Name;
        
		if ( $Type == 'folder' ) 
		{
			if (@mkdir($PMID  . "/" . $Name))
			{
				$item['status'] = 1;
			}
			else {
				        $item['status'] = 0;
			}
		}
		else {
			if (@file_put_contents( $PMID  . "/" . $Name ,'0')!=0)
			{
				        $item['status'] = 1;
			}else
			{
				        $item['status'] = 0;
			}
		}
        return $item;  
    }
    
    public function getFile( $path )
    {
    	if ( file_exists ( $path ) ) {
         
            header('Content-Description: File Transfer');
            header('Content-Type: application/octet-stream');
            header('Content-Disposition: attachment; filename='.basename($path));
            header('Content-Transfer-Encoding: binary');
            header('Expires: 0');
            header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
            header('Pragma: public');
            header('Content-Length: ' . filesize($path));
            ob_clean();
            flush();
            readfile($path);
         
            return ( true );
               
         } else {
         
            return ( false );
            
         }
    }
    
	function get_dirs($dir = '' ){ 
	$result = array();
	if ( $dir == '' )
	{
		$usersDAO = new Application_Model_Users();
    	$userId = $usersDAO->getCurrentUser()->id;
    	$path =  APPLICATION_PATH . "/store/$userId" ;  
    	if ( !is_dir( $path )  )  mkdir($path); 
		$dir = $path;
	}
    if (!isset($dirs)){$dirs = '';} 
    if(substr($dir,-1) !== '\\'){$dir .= '\\';} 
    if ($handle = opendir($dir)){ 
        while (false !== ($file = readdir($handle))){
        	$item = array('data'=>'titile', 'children'=>array()); 
            if (filetype($dir.$file) === 'dir' && $file != "." && $file != ".."){ 
                clearstatcache(); 
                
                $item['data'] = $file;
                $item['data'] = iconv("cp1251", "UTF-8" ,$item['data'] ); 
                $item['attr']['rel'] = 'folder';
                $item['attr']['id'] = $dir . $file;
                $item['attr']['id'] = iconv("cp1251", "UTF-8" ,$item['attr']['id'] );
                $item['type'] = 'folder'; 
                $item['children'] = $this->get_dirs($dir . $file);
                $result[] = $item;
            } 
            elseif($file != "." && $file != "..")
            {
            	$item['data'] = $file;
            	$item['data'] = iconv("cp1251", "UTF-8" ,$item['data'] );
            	$item['attr']['rel'] = 'file';
            	$item['attr']['id'] = $dir . $file;
            	$item['attr']['id'] = iconv("cp1251", "UTF-8" ,$item['attr']['id'] );
            	$item['type'] = 'default';
            	$result[] = $item;
            }
        } 
        closedir($handle); 
    }
//     $result = iconv("cp1251", "UTF-8" , $result);
    return  $result;
}

}

